package com.example.rbac5.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.rbac5.demo.annotations.HasPower;
import com.example.rbac5.demo.entity.Power;
import com.example.rbac5.demo.service.PowerService;
import com.example.rbac5.demo.service.RolePowerService;
import com.example.rbac5.demo.service.RoleService;
import com.example.rbac5.demo.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2023-11-08
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePowerService rolePowerService;

    @Autowired
    private PowerService powerService;

    @GetMapping("add")
    @HasPower("user:add")
    public void add(){
        log.info("add...");
    }

    @GetMapping("list")
    @HasPower("user:list")
    public void list(){
        log.info("list...");
    }

    @GetMapping("delete")
    @HasPower("user:delete")
    public void delete(){
        log.info("delete...");
    }

    @GetMapping("login")
    public void login(){
        //获取权限列表，存入redis中
        String userId="10002";

        //userId->roleId
       String roleId= userRoleService.findRoleIdByUserId(userId);
       //roleId-> 获取当前用户所有的powerId
        List<String> powerIdList=rolePowerService.findPowerIdListByRoleId(roleId);
        //通过所有的powerId -> 权限列表->提取表达式
        LambdaQueryWrapper<Power> wrapper=new LambdaQueryWrapper();
        wrapper.in(Power::getId,powerIdList);

        List<Power> powerList=powerService.list(wrapper);

        log.info("{}",powerList);

        String expressList="";

        for (int i = 0; i < powerList.size(); i++) {
            if(i==(powerList.size()-1)){
                expressList+=powerList.get(i).getExpress();
            }else{
                expressList+=powerList.get(i).getExpress()+",";
            }

        }
        redisTemplate.opsForValue().set("powerList:"+userId,expressList);
    }
}
